package com.waidi.clothespad.common;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.ParcelUuid;
import android.os.StatFs;
import android.support.annotation.NonNull;
import android.text.format.Formatter;
import android.util.Log;

import com.waidi.clothespad.fragment.FragGongyishipin;
import com.waidi.clothespad.fragment.FragHouDaoqc;
import com.waidi.clothespad.fragment.FragHouProduct;
import com.waidi.clothespad.fragment.FragLineOut;
import com.waidi.clothespad.fragment.FragShenglineqc;
import com.waidi.clothespad.fragment.FragShenglineqc2;
import com.waidi.clothespad.fragment.FragShishishuju;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by ll on 2018/1/10.
 */

public final class Config {

    private static String TAG ="Config: ";
    public static float transparency= (float)0.10f; //透明度

    public static String ver = null;
    public static String qrcode=null;

    public static boolean dg_server_add_changed ;
    public static String current_hangerid;

    public static String pctime;


    public static String Clothesath=null;
    public static String videopath =null;
    public static String urltxt=null;
    public static String devtxt=null;
    public static String workerinfotxt=null;
    public static String realinfotxt=null;

    public static String gylxttxt=null;
    public static String dpsProuductIndotxt=null;

    public static String dpsHoudaodpsProuductIndotxt = null;

    public static String faultinfotxt =null;

    public static String imagepath=null;

    public static String apkpath=null;

    public static RealData realinfo = new RealData();
    public static RfidWorkerInfo rfidWorkerInfo =new RfidWorkerInfo();

    public static HashMap<String,Video> videoMap = new HashMap<String,Video>();
    public static HashMap<String,Qcinfo> qcinfoHashMap =new HashMap<String,Qcinfo>();
    public static ArrayList<QcCommit> qcCommitArrayList = new ArrayList<QcCommit>();
    public static Qccxzjlxt qccxzjlxt = new Qccxzjlxt();
    public static ArrayList<FaultInfo> faultInfoArrayList = new ArrayList<>();

    public static StyeNumInfo styeNumInfo= new StyeNumInfo();


    //UI 和 handler
    public static Handler MainActivityHandler = null;
    public static FragShishishuju fragShishishuju =null;
    public static FragGongyishipin fragmentvideo = null;

    public static FragHouProduct fragmenthoudao = null;
    public static FragHouDaoqc fragmenthoudaoqc=null;
    public static FragShenglineqc fragShenglineqc = null;

    public static FragShenglineqc2 fragShenglineqc2 = null;

    public static FragLineOut fragLineOut= null;


    public static int fragment_index=0;

    public static boolean webscoekt_conn ;



    public static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public static Queue<RfidData>  hgrfiddataqueue= new LinkedList<RfidData>();

    public static Queue<RfidData>  orderrfiddataqueue= new LinkedList<RfidData>();

    public static Queue<RfidData>  workerrfiddataqueue= new LinkedList<RfidData>();



    public static DevConfig devConfig =null;
    public static QrCodeInfo qrCodeInfo=null;

    public static int RePairFlag = 0;
    public static int RePairCode = 0;//单个工序返修
    public static String RePairCodeString = "";//多个工序返修
    public static ArrayList<String>RePairCodeArrayList =  new ArrayList<String>();

    public static int Workerinfosyncflag = 0;
    public static int hangerinfosyncflag = 0;

    public static String globalrealorderid="";
    public static String globalrealhangerid="";
    public static String schemaLineNum = "" ; //生产计划方案


    private Context context;

   // public DpsInterface dpsInterface =null ;

    public  Config(Context context)
    {
        this.context = context;
    }
    public void init()
    {


        try
        {
            ver = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        }
        catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
        }
        devConfig = new DevConfig();
        dg_server_add_changed = false;
        webscoekt_conn = false;

    try {





        qrcode = getUniquePsuedoID();

        File file = new File(Environment.getExternalStorageDirectory() + "/Tps10/");
        if (!file.exists())
        {
            Log.d("result", "create result:" + file.toString() + ":" + file.mkdirs());
            Clothesath = file.toString();
        }
        else
        {
            Clothesath = file.toString();
        }
        if(file.canExecute()==false)
        {
            Log.e(TAG,file.toString()+"不可执行");
            Log.e(TAG,"系统获取内部存储路径错误，请尝试重新启动终端");
            new MessageToUi().send(600,"mount","系统获取内部存储路径错误，请尝试重新启动终端",MainActivityHandler);
        }


        Log.e(TAG,Clothesath);


        qrCodeInfo=new QrCodeInfo();

        videopath = Clothesath +"/video";
        imagepath = Clothesath+"/image";
        apkpath = Clothesath+"/apk";

        devtxt = Clothesath+"/devconf.txt";
        gylxttxt= Clothesath+"/gylxt.txt";
        faultinfotxt = Clothesath+"/faultinfo.txt";
        dpsProuductIndotxt = Clothesath+"/dpsproductinfo.txt";
        dpsHoudaodpsProuductIndotxt = Clothesath+"/dpshoudaoproductinfo.txt";

        workerinfotxt = Clothesath+"/workerinfo.txt";
        realinfotxt = Clothesath+"/realinfo.txt";



        File file1 = new File(videopath);
        if(!file1.exists())
        {
            Log.d("result", "create result:" +file1.toString()+":"+ file1.mkdirs());
        }
        videopath = file1.toString();

        if(videopath==null)
            return;

        File file12 = new File(imagepath);
        if(!file12.exists())
        {
            Log.d("result", "create result:" +file12.toString()+":"+ file12.mkdirs());
        }
        imagepath = file12.toString();

        if(imagepath==null)
            return;



        File file13 = new File(apkpath);
        if(!file13.exists())
        {
            Log.d("result", "create result:" +file13.toString()+":"+ file13.mkdirs());
        }
        apkpath = file13.toString();

        if(apkpath==null)
            return;


        urltxt = videopath+"/url.txt";
        File file2 = new File(urltxt);
        File file3 = new File(devtxt);
        File file4 = new File(realinfotxt);
        File file5 = new File(workerinfotxt);



     /*   if (!file2.exists())
            {
                Log.d("result", "create result:" +file2.toString()+":"+ file2.createNewFile());
            }
            urltxt = file2.toString();*/

            if (!file3.exists())
            {
                Log.d("result", "create result:" +file3.toString()+":"+ file3.createNewFile());
            }
            devtxt = file3.toString();

            if (!file4.exists())
            {
                Log.d("result", "create result:" +file4.toString()+":"+ file4.createNewFile());
            }
            realinfotxt = file4.toString();


            if (!file5.exists())
            {
                Log.d("result", "create result:" +file5.toString()+":"+ file5.createNewFile());
            }
            workerinfotxt = file5.toString();

        }catch (IOException e)
        {
            e.printStackTrace();
            MyToast.showToast(context,e.toString());
            Log.e(TAG,e.toString());
        }

       // loadurltxt();
        loaddevtxt();
        rfidworkerinfoload();
    }
    public void loadurltxt()
    {
        if(urltxt==null)
            return;
        File url = new File(urltxt);
        try {
            FileInputStream in = new FileInputStream(url);
            int len = 0;
            byte[] buf = new byte[1024];
            String  strbuf;
            String  strjson="";
            while((len=in.read(buf))!=-1){
                //System.out.println(new String(buf,0,len));
                strbuf = new String(buf,0,len);
                strjson = strjson + strbuf;
            }
            in.close();

            if(strjson==null)
                return;
            JSONObject jsonObj = new JSONObject(strjson);
            if(jsonObj==null)
                return;

            JSONArray videoArray = jsonObj.getJSONArray("info");
            if(videoArray==null)
                return;
            if(videoArray.length()!=0)
                videoMap.clear();
            for (int i=0;i<videoArray.length();i++)
            {
                JSONObject s= (JSONObject)videoArray.get(i);
                Video tmp = new Video(null,null,null,null);
                tmp.localfile =s.optString("video_name");
                tmp.urlStl = s.optString("video_url");
                tmp.md5 = s.optString("md5");
                videoMap.put(Integer.toString(i),tmp);
                Log.i(TAG,tmp.localfile);
                Log.i(TAG,tmp.urlStl);
            }
        }
        catch (JSONException je)
        {
            je.printStackTrace();
        }catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static  void rfidworkerinfosave()
    {
        try
        {
            JSONObject rfidworker = new JSONObject();
            rfidworker.put("name", rfidWorkerInfo.workername);
            rfidworker.put("code", rfidWorkerInfo.workernum);
            rfidworker.put("time", rfidWorkerInfo.logtime);
            rfidworker.put("line", rfidWorkerInfo.line);
            String jsonstr = rfidworker.toString();
            if(workerinfotxt==null)
                return;
            OutputStream os = new FileOutputStream(workerinfotxt);
            byte [] bytes = jsonstr.getBytes("UTF-8");
            os.write(bytes,0,bytes.length);
            //关闭流
            os.close();
            os.flush();
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        catch (IOException i)
        {
            i.printStackTrace();
        }
    }

    public static void rfidworkerinfoload()
    {
        if(workerinfotxt==null)
            return;
        File file = new File(workerinfotxt);
        try {
            FileInputStream in = new FileInputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            String  strbuf;
            String  strjson="";
            while((len=in.read(buf))!=-1){
                strbuf = new String(buf,0,len);
                strjson = strjson + strbuf;
            }
            in.close();
            if(strjson==null)
                return;
            JSONObject jsonObj = new JSONObject(strjson);
            if(jsonObj==null)
                return;
            rfidWorkerInfo.workername = jsonObj.optString("name");
            rfidWorkerInfo.workernum = jsonObj.optString("code");
            rfidWorkerInfo.logtime = jsonObj.optString("time");
            rfidWorkerInfo.line = jsonObj.optString("line");
            Log.i(TAG,rfidWorkerInfo.workername+ " "+rfidWorkerInfo.workernum+
                    " "+rfidWorkerInfo.line+ " "+rfidWorkerInfo.logtime);
        }
        catch (JSONException je)
        {
            je.printStackTrace();
        }catch (IOException e)
        {
            e.printStackTrace();
        }


    }


    public void  loaddevtxt()
    {
/*        {
            "devid": "1",
                "addr": "192.168.1.2",
                "port": "8088"
        }*/

        if(devtxt==null)
            return;
        File file = new File(devtxt);
        try {
            FileInputStream in = new FileInputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            String  strbuf;
            String  strjson="";
            while((len=in.read(buf))!=-1){
                //System.out.println(new String(buf,0,len));
                strbuf = new String(buf,0,len);
                strjson = strjson + strbuf;
            }
            in.close();
            if(strjson==null)
                return;
            JSONObject jsonObj = new JSONObject(strjson);
            if(jsonObj==null)
                return;



            devConfig.devid = jsonObj.optString("devid");
            devConfig.addr = jsonObj.optString("addr");
            devConfig.line_num = jsonObj.optString("line");
           // devConfig.port = jsonObj.getString("port");

            Config.devConfig.port = "8088";
            devConfig.web_addr = jsonObj.optString("webaddr");


            Log.i(TAG,devConfig.devid+ " "+devConfig.addr+ " "+devConfig.web_addr+ " "+devConfig.line_num);
        }
        catch (JSONException je)
        {
            je.printStackTrace();
        }catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static  void savedevtxt()
    {
        try
        {
            JSONObject devconfig = new JSONObject();
            devconfig.put("devid", devConfig.devid);
            devconfig.put("addr", devConfig.addr);
            devconfig.put("webaddr", devConfig.web_addr);
            devconfig.put("line", devConfig.line_num);

            String jsonstr = devconfig.toString();
            if(devtxt==null)
                return;
            OutputStream os = new FileOutputStream(devtxt);
            byte [] bytes = jsonstr.getBytes("UTF-8");
            os.write(bytes,0,bytes.length);
            //关闭流
            os.close();
            os.flush();
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        catch (IOException i)
        {
            i.printStackTrace();
        }
    }




    public final class Video
    {
        public String localfile;
        public  String urlStl;
        public String md5;
        public String filesize;
        public Video(String localfilename,String urlStlname,String md5,String filesize)
        {
            this.localfile = localfilename;
            this.urlStl = urlStlname;
            this.md5 = md5;
            this.filesize = localfile;
        }
    }

    public final class Qcinfo
    {

        public String defect_id; //缺陷ID
        public String defect_desc;//缺陷描述
        public String recProc_solu; //解决方法

        public Qcinfo(String defect_id,String defect_desc,String recProc_solu)
        {
            this.defect_id = defect_id;
            this.defect_desc = defect_desc;
            this.recProc_solu = recProc_solu;
        }
    }

    public final class QcCommit
    {
        //
        public String defect_desc;
        public String defect_num;
        public QcCommit(String defect_desc,String defect_num)
        {
            this.defect_desc = defect_desc;
            this.defect_num = defect_num;

        }
    }




    public final class DpsInterface
    {
        public String update = null;
        public String changxianqc_comitproduct = null;
        public String houdao_productInfo = null;

        public String faultinfoget =null;
        public String logon = null;

        public String qrcode= null;
        public String videlist =null;

        public String workerproduct =null;

        public DpsInterface(String addr)
        {
            update = "http://"+addr+"/basic/config/getAppAddressAndVer";
            changxianqc_comitproduct="http://"+addr+"/pis/defect/save?qrCode="+getUniquePsuedoID()+"&workNum="+Config.rfidWorkerInfo.workernum;
            houdao_productInfo = "http://" + addr+"/pis/orderPaSub/getStationInfoByPannel?qrCode="+getUniquePsuedoID();
            faultinfoget = "http://" + addr+"/basic/defectType/getAll";
            logon = "http://" + addr+"/basic/worker/findByWorNum?";
            qrcode = "http://" + addr+"/basic/equipment/findByQrCode?qrCode="+getUniquePsuedoID();
            videlist = "http://" + addr+"/basic/terminalFile/getEvList?styNum=";
            workerproduct = "http://"+addr+"/pis/productLog/getListByWorkNum?qrCode="+getUniquePsuedoID()+"&workNum="+Config.rfidWorkerInfo.workernum;
        }

    }


    public static String getUniquePsuedoID()
    {
        String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
        String serial = null;
        try
        {
            serial = android.os.Build.class.getField("SERIAL").get(null).toString();
            // Go ahead and return the serial for api => 9
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString().toUpperCase();
        }
        catch (Exception e)
        {
            // String needs to be initialized
            e.printStackTrace();
            serial = "serial"; // some value
        }

        // Thanks @Joe!
        // http://stackoverflow.com/a/2853253/950427
        // Finally, combine the values we have found by using the UUID class to create a unique identifier
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString().toUpperCase();
    }

    /**
     * 获取手机外部可用存储空间
     *
     * @param context
     * @return 以M,G为单位的容量
     */
    public static String getAvailableExternalMemorySize(Context context) {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        long sum = blockSize*availableBlocks;
        if(sum<1024*1024*1024) //剩余空间小于1G 清空视频缓存
        {
            File dirFile = new File(videopath);

            File[] files = dirFile.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                f.delete();
            }
        }
        return Formatter.formatFileSize(context, blockSize * availableBlocks);
    }

    public static Long getAvailableExternalMemorySizeByte(Context context) {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();



        return blockSize*availableBlocks;

   }


}
